package bll

import (
	"context"
	"maya-service/store/mysql"

	"maya-service/model"
	"maya-service/model/entity"
	"maya-service/model/mapping"
	"maya-service/store"
	"time"
)

type gameLevel struct {
	iGameLevel store.IGameLevel
}

var GameLevel = &gameLevel{
	iGameLevel: mysql.GameLevel,
}

func init() {
	Register(GameLevel)
}

func (a *gameLevel) init() func() {
	return func() {}
}

// Create
func (a *gameLevel) Create(ctx context.Context, in *model.GameLevelCreateRequest) error {
	var (
		err error
	)
	c := buildGameLevel(in)
	_, err = a.iGameLevel.Create(ctx, c)
	return err
}

// Update
func (a *gameLevel) Update(ctx context.Context, in *model.GameLevelUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	if in.Desc != nil {
		dict["desc"] = in.Desc
	}

	if in.Weight != nil {
		dict["weight"] = in.Weight
	}

	if in.Type != nil {
		dict["type"] = in.Type
	}

	if in.ParentId != nil {
		dict["parent_id"] = in.ParentId
	}

	if in.QuestionCount != nil {
		dict["question_count"] = in.QuestionCount
	}

	if in.EssayQuestionCount != nil {
		dict["essay_question_count"] = in.EssayQuestionCount
	}

	if in.Threshold != nil {
		dict["threshold"] = in.Threshold
	}

	if in.StarZone != nil {
		dict["star_zone"] = in.StarZone
	}

	if in.Image != nil {
		dict["image"] = in.Image
	}

	if in.CreatedAt != nil {
		dict["created_at"] = in.CreatedAt
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// do other update here
	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt
	return a.iGameLevel.Update(ctx, in.Id, dict)
}

// Delete
func (a *gameLevel) Delete(ctx context.Context, in *model.GameLevelDeleteRequest) error {
	return a.iGameLevel.Delete(ctx, in.Id)
}

// List
func (a *gameLevel) List(ctx context.Context, in *model.GameLevelListRequest) (*model.GameLevelListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.GameLevel
		out   = &model.GameLevelListResponse{}
	)

	if total, list, err = a.iGameLevel.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = mapping.GameLevelsEntityToDto(list)

	return out, nil
}

// Find
func (a *gameLevel) Find(ctx context.Context, in *model.GameLevelInfoRequest) (*model.GameLevelInfo, error) {
	var (
		err  error
		data *entity.GameLevel
		out  = &model.GameLevelInfo{}
	)

	if data, err = a.iGameLevel.Find(ctx, in); err != nil {
		return nil, err
	}

	out = mapping.GameLevelEntityToDto(data)
	return out, nil
}

// buildGameLevel build entity
func buildGameLevel(in *model.GameLevelCreateRequest) *entity.GameLevel {

	ety := &entity.GameLevel{}

	ety.Desc = in.Desc

	ety.Weight = in.Weight

	ety.Type = in.Type

	ety.ParentId = in.ParentId

	ety.QuestionCount = in.QuestionCount

	ety.EssayQuestionCount = in.EssayQuestionCount

	ety.Threshold = in.Threshold

	ety.StarZone = in.StarZone

	ety.Image = in.Image

	ety.CreatedAt = time.Now().Unix()

	ety.UpdatedAt = in.UpdatedAt

	return ety
}
